<template>
  <div class="card-edit-index">
    <!-- header -->
    <el-header class="clear-ed">
      <index-header
        :options="{ ...optionsNotTp, status: status }"
        @setting="click2ShowSetting"
        @preview="click2SaveCardSite"
        @saveCover="click2SaveCover"
        @online="click2Online">
      </index-header>
    </el-header>

    <!-- top card-type-lists 组件类型列表 -->
    <TopContainer>
      <UnitOne v-if="curPanel == -1" :tab="'Card类型'" :lists="pluginsCardTypeLists" @clickAction="onAddCard"></UnitOne>
      <UnitOne v-if="curPanel == -1" :tab="'业务Card类型'" :lists="pluginsCardJYTypeLists" @clickAction="onAddCard"></UnitOne>
      <UnitOne v-if="curPanel > -1" :tab="'Panel类型'" :lists="pluginsPanelTypeLists" @clickAction="onAddPanel"></UnitOne>
    </TopContainer>

    <!-- content -->
    <div class="card-edit-content">
      <!-- card-edit-left web左侧编辑面板 -->
      <CardEditLeft class="pos-re"></CardEditLeft>

      <!-- card-edit-index-box 手机屏幕 -->
      <CardEditIndexBox class="pos-re" @resize="val => handlerResize(val)"></CardEditIndexBox>

      <!-- card-edit-right web右侧编辑面板 -->
      <CardEditRight class="pos-re"></CardEditRight>

      <!-- card-edit-event -->
      <CardEditEvent></CardEditEvent>

      <!-- card-edit-more -->
      <CardEditMore></CardEditMore>
    </div>

    <!-- Conversion -->
    <Conversion :objData="siteData" :jurisdiction="group==1" @change="handler2ConversionChange"></Conversion>
  </div>
</template>

<script>
  import IndexHeader from '@/views/child/header/IndexHeader.vue';
  import TopContainer from '@/views/card/components/top/TopContainer.vue';
  import UnitOne from '@/views/card/components/top/UnitOne.vue';
  import CardEditRight from '@/views/card/right/CardEditRight.vue';
  import CardEditLeft from '@/views/card/left/CardEditLeft.vue';
  import CardEditIndexBox from '@/views/card/content/CardEditIndexBox.vue';
  import CardEditEvent from '@/views/card/event/CardEditEvent.vue';
  import CardEditMore from '@/views/card/more/CardEditMore.vue';
  import Conversion from '@/views/card/conversion/index.vue';

  import { coverImg } from '@/views/card/js/mixins/cover-img.js';
  import { dynamicsLoadScript } from '@/views/card/js/mixins/dynamics-load-script.js';
  import { MOBILE_WID_HEI } from '@/views/card/js/config/card-page-config.js';

  import { EventBus } from '@/store/index.js';
  import { BUSINESS_NO_CARD } from '@/views/card/js/data/cardSiteData';
  import CardCommonComputed from '@/views/card/js/mixins/card-common-computed.js';

  import { CardTypeDatas, _getAllCardTypes } from "@/views/card/js/data/cardDatas/index.js";

  import { PanelTypeDatas, PanelTypeLists } from '@/views/card/js/data/panelDatas';
  import { guid, getValueFromXml } from '@/plugins/utils.js';
  import { isNumber } from '@/utils/public.js';
  import { mapState, mapActions } from 'vuex'
  import { onBeforeUnmount } from 'vue'
  import { useStore } from "vuex";

  export default {
    setup() {
      onBeforeUnmount(() => {
        const store = useStore();

        // clear cardComponents
        store.commit("cardComponents/clear");

        // clear panelComponents
        store.commit("cardComponents/panelComponents/clear");
      })
    },
    name: 'cardEditIndex',
    mixins: [CardCommonComputed, dynamicsLoadScript, coverImg],
    data() {
      return {
        /* header */
        optionsNotTp: {  // IndexHeader tab 显示/隐藏
          arrBtns: [0, 1, 1, 1, 0, 1],
          transparent: false,
          status: '',
        },

        /* cardSite */
        cardSiteId: '',

        /* config */
        limit: 10,
        bIsSiteDataChanged: false,
        scale: 1,  // phone 缩放
      }
    },
    computed: {
      ...mapState({
        group: (state) => state.user.user.group,
        curPageData: state => state.cardComponents.curPageData,
        containerId: state => state.cardComponents.siteData.attrs.containerid,
        siteData: state => state.cardComponents.siteData,
        status: state => state.cardComponents.sitePreshowData.status,  // online 2-下线，1-上线
        fileUploadData: state => state.components.fileUploadData,
        pageInfo: state => _.cloneDeep(state.cardComponents.siteData.attrs),

        panels: state => _.cloneDeep(state.cardComponents.siteData.panels) || [],
        curPanel: state => state.cardComponents.panelComponents.curPanel,
      }),
      pluginsCardTypeLists() {  // top card type lists
        /* eslint-disable */
        const reg = /^CARD_[0-9]+$/;
        /* eslint-enable */
        return _getAllCardTypes(reg);
      },
      pluginsCardJYTypeLists() {
        /* eslint-disable */
        const reg = /^CARD_JY[0-9]+$/;
        /* eslint-enable */
        return _getAllCardTypes(reg);
      },
      pluginsPanelTypeLists() {
        return PanelTypeLists;
      },
    },
    components: {
      IndexHeader,
      TopContainer,
      UnitOne,
      CardEditRight,
      CardEditLeft,
      CardEditIndexBox,
      CardEditEvent,
      CardEditMore,
      Conversion,
    },
    created() {
      // 1. cardSiteId
      this.cardSiteId = this.$route.params.id;
      // console.log(this.$route.params);

      // 2. init site data
      this.initSiteData();
    },
    methods: {
      ...mapActions({
        getCardSite: 'cardComponents/getCardSite',
        getCardSitePreshow: 'cardComponents/getCardSitePreshow',
        getCardSitePreshow4Qrcode: 'cardComponents/getCardSitePreshow4Qrcode',
        updateCardLists: 'cardComponents/updateCardLists',
        saveCardSite: 'cardComponents/saveCardSite',
        onlineSite: 'cardComponents/onlineSite',
        getFileUploadData: 'components/getFileUploadData',
        updateCardPageInfo: 'cardComponents/updateCardPageInfo',
        updateCardSiteData: 'cardComponents/updateCardSiteData',

        updatePanelLists: 'cardComponents/panelComponents/updatePanelLists',
      }),

      /* init */
      async initSiteData() {
        // 2. getCardSite
        await this.getCardSite({
          id: this.cardSiteId,
        });

        // 3. get preshow
        await this.getCardSitePreshow({
          id: this.cardSiteId,
        });

        // 4. get params
        this.getFileUploadData();
      },
      handlerResize(scale) {
        this.scale = scale;
      },

      /* setting */
      click2ShowSetting() {
        EventBus.$emit('layoutMoreShow', {});
      },

      /* 数据保存 */
      async click2SaveCardSite() {
        // 0. appKey ?
        // const wbAppKey = this.pageInfo.wb_appkey;
        // if( !isString( wbAppKey ) || wbAppKey == '' ) {
        //   this.handlerAppKey();
        //   return;
        // }

        // 1. save card site data
        await this.saveCardSite({
          callback: () => {
            // 2. show tips
            this.$notify({
              title: '提示',
              message: '保存成功',
              type: 'success'
            });
          }
        });
      },
      handlerAppKey() {
        this.$alert('请填入微博 AppKey', 'AppKey', {
          confirmButtonText: '确定',
          // callback: action => {
          //   this.$message({
          //     type: 'info',
          //     message: `action: ${ action }`
          //   });
          // }
        });
      },

      /* 上/下线 */
      async click2Online() {
        // 1. online 2-下线，1-上线
        await this.onlineSite({
          id: this.cardSiteId,
          status: this.status == '2' ? '1' : '2',
        })

        // 2. 获取更新 sitePreshowData; 更新 shared_text_qrcode
        await this.getCardSitePreshow4Qrcode({
          id: this.cardSiteId,
        })
      },

      /* 保存封面 */
      click2SaveCover() {
        // 2. cover shot
        this.print(
          document.querySelector('#card-phone-screen'),
          ( MOBILE_WID_HEI.width / 2 + MOBILE_WID_HEI.border_width * 2 ) * this.scale,
          ( MOBILE_WID_HEI.height / 2 ) * this.scale,
          1,
        );
      },
      onSuccess(res) {
        // 1. get url
        let url = getValueFromXml(res);
        url = _.replace(url, 'http', 'https');
        url = _.replace(url, 'file', 'static');
        url = _.replace(url, '.s3.sinaapp.com', '');

        // 2. update pageInfo
        this.updateCardPageInfo({
          ...this.pageInfo,
          thumb: url,
        });

        // 3. save card site data
        this.click2SaveCardSite();
      },
      onError(e){
        // 1. error
        console.log(e);
      },

      /* update */
      onAddCard(item) {
        // 0. 单页限制添加 limit 个card
        if( !this.bIsParentEditable && !this.bIsCardTypeOfComb(this.curSelectCardType) ) {
          if( this.curPageData.length >= this.limit )
            return alert('为了体验更流畅，单页的 CardList 数量请保持在 ' + this.limit + ' 个及以下。');
        }

        // 1. 当前在 card11 下编辑；或当前 select 为 CARD_11
        // console.log('item: ', item);
        // console.log('type: ', item.type);
        // console.log('curSelectCardType: ', this.curSelectCardType);
        // console.log('this.curSelectParentCardIndex: ', this.curSelectParentCardIndex);
        // if (item.type == 'CARD_11') return;

        if( ( this.bIsParentEditable || this.bIsCardTypeOfComb(this.curSelectCardType) ) && this.bIsCardTypeOfComb(item.type) ) {
          return alert('组合类型Card 中，请勿再添加 组合Card');
        }
        if( ( this.bIsParentEditable || this.bIsCardTypeOfComb(this.curSelectCardType) ) && ( item.type == 'CARD_JY0001' || item.type == 'CARD_JY0002' ) ) {
          return alert('组合类型Card 中，请勿添加 业务组合Card');
        }

        // 2. new card
        // TODO: 1. 当已有选择的 card 时，添加的新 card 位于上/下？
        // TODO: 2. if item.type exist?
        // TODO: 3. card11?
        // TODO: 4. card_type_name
        let newCard = _.cloneDeep(CardTypeDatas[item.type].data);  // 深拷贝，不改变原对象的值
        const itemId = guid();
        newCard.itemid = BUSINESS_NO_CARD + '_-_' + this.cardSiteId + '_-_' + itemId;
        newCard.Idx_index = this.cardLists.length.toString();
        newCard.Idx_name = itemId;

        // 2.1 if item.type 特殊处理？
        newCard = this._getHandlerNewCardByItemType(newCard);

        // 3. new cardLists
        let newCardLists = _.cloneDeep(this.cardLists);
        newCardLists = this._getNewCardLists(newCardLists, newCard);

        // 4. update cardLists to state
        this.updateCardLists([
          ...newCardLists,
        ]);
      },
      _getHandlerNewCardByItemType(newCard) {
        // 1. CARD_2001
        if( 'CARD_2001' == 'CARD_' + newCard.card_type ) {
          newCard.card_id = this.cardSiteId + '-' + newCard.itemid
          newCard.support_common_params.topic_id =  // 14位数: 20000000000000 -- 29999999999999
            this.cardSiteId + '-' + this._getNumId( 14, Math.pow(10, 14) - 1 - Math.pow(10, 13) * 9, Math.pow(10, 13) * 2 );
          newCard.support_common_params.Idx_name = newCard.Idx_name;
          newCard.left.support_params.id =  // 14位数: 20000000000000 -- 29999999999999
            this._getNumId( 14, Math.pow(10, 14) - 1 - Math.pow(10, 13) * 9, Math.pow(10, 13) * 2 );
          newCard.left.support_params.com_id = guid();
          newCard.right.support_params.id = newCard.left.support_params.id + 1;
          newCard.right.support_params.com_id = guid();
        }
        return newCard;
      },
      _getNumId(exponent, times, base) {
        const numExponent = isNumber(exponent) ? exponent : 11;
        const numTimes = isNumber(times) ? times : Math.pow(10, numExponent);
        const numBase = isNumber(base) ? base : 0;
        return Math.floor( Math.random() * numTimes + numBase );
      },
      _getNewCardLists(newCardLists, newCard) {
        // 1. 编辑列表（即编辑组合Card）
        if(this.bIsParentEditable) {
          if(this.curSelectParentCardIndex < 0 || !newCardLists[this.curSelectParentCardIndex]) return newCardLists;
          const curSelectParentCard = newCardLists[this.curSelectParentCardIndex];

          // 1.1 区分 Card 11 / Card 86，做不同处理
          if( 'CARD_' + curSelectParentCard.card_type === 'CARD_11' ) {
            newCardLists[this.curSelectParentCardIndex].card_group = this._handlerAddNewCard(
              newCardLists[this.curSelectParentCardIndex].card_group,
              newCard,
              this.curSelectCardIndex,
            );
          }

          else if( 'CARD_' + curSelectParentCard.card_type === 'CARD_86' ) {
            if( 'CARD_' + newCard.card_type != 'CARD_80' &&
              'CARD_' + newCard.card_type != 'CARD_87' &&
              'CARD_' + newCard.card_type != 'CARD_128' &&
              'CARD_' + newCard.card_type != 'CARD_160' ) {
                alert('组合类型Card 86 中只能添加 Card 80 / Card 87 / Card 128 / Card 160');
                return newCardLists;
            } else {
              newCardLists[this.curSelectParentCardIndex].sub_cards = this._handlerAddNewCard(
                newCardLists[this.curSelectParentCardIndex].sub_cards,
                newCard,
                this.curSelectCardIndex,
              );
            }
          }

          else if( 'CARD_' + curSelectParentCard.card_type === 'CARD_118' ) {
            if( 'CARD_' + newCard.card_type != 'CARD_119'  ) {
                alert('组合类型Card 118 中只能添加 Card 119');
                return newCardLists;
            } else {
              newCardLists[this.curSelectParentCardIndex].items = this._handlerAddNewCard(
                newCardLists[this.curSelectParentCardIndex].items,
                newCard,
                this.curSelectCardIndex,
              );
            }
          }
        }
        // 2. 非编辑列表，但当前 选择/操作的Card 为 组合类型
        else if( this.bIsCardTypeOfComb(this.curSelectCardType) && !this.bIsCardTypeOfComb('CARD_' + newCard.type) ) {
          // 2.1 区分 Card 11 / Card 86，做不同处理
          if( this.curSelectCardType == 'CARD_11' ) {
            newCardLists[this.curSelectCardIndex].card_group = this._handlerAddNewCard(
              newCardLists[this.curSelectCardIndex].card_group,
              newCard,
            );
          }

          else if( this.curSelectCardType == 'CARD_86' ) {
            if( 'CARD_' + newCard.card_type != 'CARD_80' &&
              'CARD_' + newCard.card_type != 'CARD_87' &&
              'CARD_' + newCard.card_type != 'CARD_128' &&
              'CARD_' + newCard.card_type != 'CARD_160' ) {
                alert('组合类型Card 86 中只能添加 Card 80 / Card 87 / Card 128 / Card 160');
                return newCardLists;
            }
            else {
              newCardLists[this.curSelectCardIndex].sub_cards = this._handlerAddNewCard(
                newCardLists[this.curSelectCardIndex].sub_cards,
                newCard,
              );
            }
          }

          else if( this.curSelectCardType == 'CARD_118' ) {
            if( 'CARD_' + newCard.card_type != 'CARD_119'  ) {
                alert('组合类型Card 118 中只能添加 Card 119');
                return newCardLists;
            } else {
              newCardLists[this.curSelectCardIndex].items = this._handlerAddNewCard(
                newCardLists[this.curSelectCardIndex].items,
                newCard,
              );
            }
          }
        }
        else {
          newCardLists = this._handlerAddNewCard(
            newCardLists,
            newCard,
            this.curSelectCardIndex,
          );
        }
        return newCardLists;
      },
      _handlerAddNewCard(lists, newItem, index) {
        if( !isNumber(index) || index < 0 ) lists.push( newItem );
        if( index >= 0 ) lists.splice( index + 1, 0, newItem );
        return this.setCardItemsIndex(lists);
      },

      /* panel update */
      onAddPanel(item) {
        let newItem = _.cloneDeep(PanelTypeDatas[item.type].data);
        let newPanel = _.cloneDeep(this.panels[this.curPanel]);

        const itemId = guid();
        newItem.itemid = BUSINESS_NO_CARD + '_-_' + this.cardSiteId + '_-_PANEL_-_' + itemId;
        newItem.Idx_index = newPanel.length.toString();
        newItem.Idx_name = itemId;

        newPanel.push(newItem);

        this.updatePanelLists(newPanel);
      },

      /* conversion */
      handler2ConversionChange(val) {
        this.updateCardSiteData(val);
      },
    },
    watch: {
      // status(newVal, oldVal) {
      //   console.log('newVal, oldVal: ', newVal, oldVal);
      //
      //   // 1. IndexHeader optionsNotTp
      //   this.optionsNotTp.status = newVal;
      // },
    },
  }
</script>

<style lang="scss">
  @import '@/assets/css/common.scss';
  @import '@/assets/css/edit.scss';

  /* 公用 class */
  .clear-ed {
    padding: 0 !important;
  }

  .display-phone-bg {
    background-image: url('//static.hd.xxx.com/jye/fe-web/images/phone-bg.png');
  }

  .drog-target {
    // border: 1px dashed red;
    opacity: 0.5;
  }

  .scroll-able {
    overflow-y: auto !important;
    overflow-x: hidden;
  }


  /* 模块 class */
  .card-edit-index {
    min-width: 1000px;
  }

  .card-edit-content {
    position: absolute;
    top: 60px;
    display: flex;
    padding: 0;
    margin: -60px 0 0 0;
    width: 100%;
    min-width: 1000px;
    height: 100vh;
    background: #fafafa;  // 避免纯白色组件丢失找不见
    // z-index: 0;
  }
</style>
